﻿@model IEnumerable<NetSurveillance.WebApp.DataServices.Models.Keyword>
@{
    ViewBag.Title = string.Format(Resources.MenuResource.SetupWizard_KeywordSetting, ViewBag.Step ?? string.Empty);
    Layout = "~/Views/Shared/_SetupWizardLayout.cshtml";
}
@section css
{
    <style type="text/css">
        .left_box
        {
            background-color: #ebebeb;
            padding: 10px;
            width: 200px;
            margin-bottom: 10px;
            margin-left: 10px;
            height: 580px;
        }
        .setup_content_left01 li.selected, .setup_content_left02 li.selected,
        .setup_content_left03 li.selected {
            background-color: blue;
            font-weight: bold;
            color: aliceblue;
        }
        #btnAddKeyword
        {
            width: 60px;
            height: 30px;
            background: url('@Url.Content("~/Content/images/setup_content_btn_bg.gif")') no-repeat;
            border: none;
            font-size: 14px;
            font-weight: bold;
            margin-top: 249px;
        }
        .editor-entry .editor-label {
            width: 100px;
        }
        #tbodyKeywords td {
            text-align: center;
        }
        .validation-summary-errors {
            text-align: center;
        }
        .setup_top {
            margin-bottom: 5px;
        }
        .lblCheckAll {
            display: inline-block;
            right: 5px;
            position: absolute;
        }
    </style>
}
@section javascript
{
    <script type="text/javascript">
        $(function() {
            $('.setup_content_left01 li').live('click', function() {
                var $li = $(this);
                if ($li.is('.selected'))
                    $li.removeClass('selected');
                else
                    $li.addClass('selected');

            });
            $('.setup_content_left02 li,.setup_content_left03 li').live('click', function() {
                var $li = $(this);
                if ($li.is('.selected'))
                    $li.removeClass('selected');
                else
                    $li.addClass('selected');
            });
            $('.setup_content_left02 li').live('click', loadFields);
            $('#chk_checkall').click(function() {
                var $liKeywords = $('.setup_content_left01 li'), $chk = $(this);
                if ($chk.is(':checked'))
                    $liKeywords.addClass('selected');
                else
                    $liKeywords.removeClass('selected');
            });
            $('#btnNewKeyword').click(openKeyword);
            $('#btnRemoveKeyword').click(deleteKeyword);
            $('#btnImportKeyword').click(importKeywords);
            $('#btnAddKeyword').click(generateKeyword);
            $('#btnSubmit').click(sumitForm);
            $('#tbodyKeywords .setup_tab_btn_del').live('click', deleteSeletedKeyword);
            $('#chkProtocol').click(function() {
                var $chk = $(this);
                if ($chk.is(':checked')) {
                    $('.setup_content_left02 li').addClass('selected');
                    loadFields();
                } else {
                    $('.setup_content_left02 li').removeClass('selected');
                    $('#ddDisplayFields').empty();
                }
            });
            $('#chkField').click(function() {
                var $chk = $(this);
                if ($chk.is(':checked'))
                    $('.setup_content_left03 li').addClass('selected');
                else
                    $('.setup_content_left03 li').removeClass('selected');
            });
        });

        function sumitForm() {
            @*if ($('#tbodyKeywords tr').size() == 0) {
                alert('@Resources.MessageResource.Alert_KeywordListIsNone');
                return false;
            }*@
            return true;
        }

        function openKeyword() {
            var title = '@Resources.Resource.Button_Add', entryId = 0;

            var opts = {
                url: '@Url.Action("SaveKeywordTemplate", "Case")?entryId=' + entryId + '&__randomDate=' + (new Date()).getTime(),
                title: title,
                height: 430,
                width: 600,
                buttons: {
                    '@Resources.Resource.Button_Save': saveEntry,
                    '@Resources.Resource.Button_Cancel': $.closeWindow
                },
                loadedFun: function () {
                    $.validator.unobtrusive.parse($.globalIds.tempWindow);
                    var $saveForm = $($.globalIds.tempFormInWindow),
                        $btnAddMore = $('<input type="button" value="@Resources.Resource.Button_Add" />'),
                        idNum = 1;
                    
                    $btnAddMore.bind('click', function () {
                        var $kwTemp = $saveForm.find('.editor-entry:first').clone(),
                            $lkRemove = $('<a href="javascript:;">移除</a>');
                        $lkRemove.bind('click', function() {
                            $(this).closest('.editor-entry').remove();
                        });
                        var newKwId = 'KeywordName' + idNum++;
                        $('#KeywordName', $kwTemp).prop('id', newKwId).prop('name', newKwId).val('');
                        $('.field-validation-valid', $kwTemp).attr('data-valmsg-for', newKwId);
                        
                        $kwTemp.append($lkRemove);
                        $(this).before($kwTemp);
                        $saveForm.removeData("validator").removeData("unobtrusiveValidation");
                        $.validator.unobtrusive.parse($.globalIds.tempWindow);
                    });
                    $('.inline-form', $saveForm).append($btnAddMore);
                }
            };
            $.openWindow(opts);
            return false;
        }

        function saveEntry() {
            var $saveForm = $($.globalIds.tempFormInWindow);
            if ($saveForm.valid()) {
                var kwArr = $.map($saveForm.find('.keywordName'), function(kwEle) {
                    return $(kwEle).val().trim();
                });
                var appendKws = filterKwInList(kwArr);
                var htmlStr = '';
                $.each(appendKws, function() {
                    htmlStr += '<li class="selected">' + this + '</li>';
                });
                $('.setup_content_left01 ul').append(htmlStr);
                $.cookie($.globalCookieNames.setupWizard.keywords, getKeywordsStr());
                $.closeWindow();
            }
            return false;
        }

        function filterKwInList(kwArr) {
            var kwInList = $.map($('.setup_content_left01 li'), function(liEle) {
                return $(liEle).text().toLocaleLowerCase();
            });
            var arr = [];
            $.each(kwArr, function() {
                if ($.inArray(this.toLocaleLowerCase(), kwInList) > -1) return true;
                arr.push(this);
            });
            return arr;
        }

        function isKeywordInSelectedList(keywordName) {
            if (!keywordName || keywordName == '') return false;
            var isSelected = false;
            $('#tbodyKeywords tr td:first-child').each(function() {
                var $td = $(this), selectedKeyword = $td.find(':hidden[id$=KeywordName]').val().trim();
                if (keywordName.toLowerCase() == selectedKeyword.toLowerCase()) {
                    isSelected = true;
                    return false;
                }
            });
            return isSelected;
        }

        function generateKeyword() {
            if (!checkSelectStatus()) return;
            $.showLoading('正在添加关键字，请等待');
            var $liEles = $('.setup_content_left01 li.selected'),
                selectedProtocolStr = $.map($('.setup_content_left02 li.selected'), function (ele) { return $(ele).data('protocol').trim(); }).toString(),
                selectedFieldStr = $.map($('.setup_content_left03 li.selected'), function(ele) { return $(ele).data('field').trim(); }).toString();
            $.each($liEles, function() {
                var keywordStr = $(this).text().trim(),
                    isInList = isKeywordInSelectedList(keywordStr);
                if (isInList && !window.confirm(keywordStr + '@Resources.MessageResource.Confirm_ReplaceKeyword'))
                    return true;//each 内return true相当于continue;
                $.ajax({
                    url: '@Url.Action("GeneratorKeywordHtml")',
                    cache: false,
                    async: false,
                    data: { KeywordName: keywordStr, Protocols: selectedProtocolStr, Fields: selectedFieldStr },
                    dataType: 'html',
                    success: function(htmlStr) {
                        if (htmlStr) {
                            if (isInList) {
                                var $originalTrEle = $('#tbodyKeywords td:has(:hidden[id$=KeywordName][value=' + keywordStr + '])').parent();
                                $originalTrEle.after(htmlStr).remove();
                            } else {
                                $('#tbodyKeywords').prepend(htmlStr);
                            }
                        }
                    }
                });
            });
            $('.setup_content_left01 li.selected,.setup_content_left02 li.selected,.setup_content_left03 li.selected').removeClass('selected');
            $.hideLoading();
        }

        function checkSelectStatus() {
            if ($('.setup_content_left01 li.selected').size() == 0) {
                alert('至少需要选择一个关键字');
                return false;
            }
            if ($('.setup_content_left02 li.selected').size() == 0) {
                alert('至少需要选择一个监控协议');
                return false;
            }
            var allProtocolFieldIsSelect = true;
            $('.setup_content_left02 li.selected').each(function() {
                var $li = $(this), selectProtocol = $li.data('protocol'),
                    $ulDisplayField = $('.setup_content_left03 ul[data-protocol=' + selectProtocol + ']');
                if ($ulDisplayField.find('li').size() > 0 && $ulDisplayField.find('li.selected').size() == 0) {
                    $li.add($ulDisplayField).addClass('hightLightBorder');
                    allProtocolFieldIsSelect = false;
                } else
                    $li.add($ulDisplayField).removeClass('hightLightBorder');
            });
            if (!allProtocolFieldIsSelect) {
                alert('标红的协议至少需要选择一个对应的字段');
                return false;
            }
            return true;
        }

        function deleteKeyword() {
            var $selectKeyWords = $('.setup_content_left01 li.selected');
            $selectKeyWords.remove();
            return false;
        }

        function getKeywordsStr() {
            var $keywords = $('.setup_content_left01 li'),
                keywordsArr = $.map($keywords, function(ele) {
                    var $keyword = $(ele);
                    return $keyword.text().trim();
                }),
                keywordsStr = ((keywordsArr && keywordsArr.length > 0) ? JSON.stringify(keywordsArr) : null);
            return keywordsStr;
        }

        function importKeywords() {
            $.ajax({
                url: '@Url.Action("GetKeywordsFromTemplate")',
                type: 'post',
                cache: false,
                dataType: 'json',
                success: function(result) {
                    if (!result) return;
                    if (result.length == 0) {
                        alert('关键字模版未进行设置');
                        return;
                    }
                    var liHtml = '',
                        kwInList = $.map($('.setup_content_left01 li'), function(liEle) {
                            return $(liEle).text().toLocaleLowerCase();
                        });
                    $.each(result, function() {
                        if ($.inArray(this.KeywordName.toLocaleLowerCase(), kwInList) == -1)
                            liHtml += '<li>' + this.KeywordName + '</li>\r\n';
                    });
                    $('.setup_content_left01 ul').append(liHtml);
                    $.cookie($.globalCookieNames.setupWizard.keywords, getKeywordsStr());
                }
            });
            return false;
        }

        function deleteSeletedKeyword() {
            var $btn = $(this);
            $btn.closest('tr').remove();
            return false;
        }
        
        function loadFields() {
            var selectedProtocols =
                $.map($('.setup_content_left02 li.selected'), function(ele) { return $(ele).data('protocol').trim(); });
            if (selectedProtocols.length == 0)
                return true;
            var selectedFields =
                $.map($('.setup_content_left03 li.selected'), function(ele) { return $(ele).data('field').trim(); });
            $('#ddDisplayFields').empty().load('@Url.Action("GetDisplayFields")',
                    $.param({ protocols: selectedProtocols }, true),
                    function() {
                        $.each(selectedFields, function() {
                            $('.setup_content_left03 li[data-field=' + this + ']').addClass('selected');
                        });
                    });
            }
    </script>
}
@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    <table cellpadding="0" cellspacing="0" border="0" width="100%">
        <tbody>
            <tr>
                <td align="left" valign="top" width="210">
                    <div class="left_box">
                        <div class="keywordContain">
                            <dl class="setup_content_left01">
                                <dt>
                                    关键字列表
                                    <label class="lblCheckAll">
                                        <input type="checkbox" id="chk_checkall"/>
                                        @Resources.Resource.Checkbox_CheckAll
                                    </label>
                                </dt>
                                <dd>
                                    <ul>
                                        @foreach (var keywordTemp in ViewBag.Keywords)
                                        {
                                            <li>@keywordTemp.KeywordName</li>
                                        }
                                    </ul>
                                </dd>
                            </dl>
                            <div class="setup_content_left_selectall">
                                <input id="btnNewKeyword" type="button" value="@Resources.Resource.Button_Add"/>
                                <input id="btnRemoveKeyword" type="button" value="@Resources.Resource.Button_Delete"/>
                                <input id="btnImportKeyword" type="button" value="@Resources.Resource.Button_Import"/>
                                <div class="setup_content_left_icons">
                                </div>
                            </div>
                        </div>
                        <dl class="setup_content_left02">
                            <dt>
                                监控协议
                                <label class="lblCheckAll">
                                    <input type="checkbox" id="chkProtocol"/>
                                    @Resources.Resource.Checkbox_CheckAll
                                </label>
                            </dt>
                            <dd>
                                <ul>
                                    @foreach (var protocol in ViewBag.Protocols)
                                    {
                                        <li data-protocol="@protocol.Name">@protocol.DisplayText</li>
                                    }
                                </ul>
                            </dd>
                        </dl>
                        <dl class="setup_content_left03">
                            <dt>
                                监控字段
                                <label class="lblCheckAll">
                                    <input type="checkbox" id="chkField"/>
                                    @Resources.Resource.Checkbox_CheckAll
                                </label>
                            </dt>
                            <dd id="ddDisplayFields">
                            </dd>
                        </dl>
                        <div class="ui-helper-clearfix"></div>
                    </div>
                </td>
                <td align="center" valign="middle" width="60">
                    <div class="setup_content_middle">
                        <input type="button" value="添加" id="btnAddKeyword" />
                    </div>
                </td>
                <td align="left" valign="top" width="*">
                    <div class="setup_content_right">
                        <div class="setup_content_right_title">&nbsp;&nbsp;关键字设置表</div>
                        <table cellpadding="0" cellspacing="0" class="setup_tab" border="0">
                            <thead>
                                <tr>
                                    <th align="center">关键字</th>
                                    <th align="center">监控协议</th>
                                    <th align="center">监控字段</th>
                                    <th align="center">是否报警</th>
                                    <th align="center">删除</th>
                                </tr>
                            </thead>
                            <tbody id="tbodyKeywords">
                                @foreach (var keyword in Model)
                                {
                                    @Html.Partial("_SingleKeyword", keyword)
                                }
                            </tbody>
                        </table>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
    <div class="buttonsContain controlBottom">
        <div class="rightContain">
            <input id="btnPreSubmit" name="preSubmit" type="submit" value="@Resources.Resource.Button_PreStep"/>
            <input id="btnSubmit" type="submit" value="@Resources.Resource.Button_FinishSetupWizard"/>
        </div>
    </div>
}
